package com.j4dream.property.dao;

import com.j4dream.property.model.PostDto;
import com.j4dream.property.model.RoleDto;
import com.j4dream.property.model.UserDto;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface UserDao {
    void insertPost(PostDto post);

    @Insert({"INSERT INTO user (email, password, name, first_name, last_name, create_time)",
            "VALUES (#{email}, #{password}, #{name}, #{firstName}, #{lastName}, #{createTime})"})
    @Options(useGeneratedKeys = true)
    void insertUser(UserDto user);

    @Insert({"<script>",
                "INSERT INTO user_role (userId, roleId) VALUES ",
                "<foreach collection='roleIds' item='roleId'>(#{userId}, #{roleId})</foreach>",
            "</script>"})
    void grantRole(@Param("userId") int userId, @Param("roleIds") List<Integer> roleIds);

    @Select("SELECT * FROM user WHERE email=#{email}")
    @Results({
            @Result(property = "roles", javaType = List.class, column = "get", many = @Many(select = "getRolesByUserId"))
    })
    UserDto findUserByEmail(String email);

    @Select("SELECT * FROM USER WHERE email=#{email} and password=#{password}")
    UserDto findUserByEmailAndPassword(@Param("email") String email, @Param("password") String password);

    @Select("SELECT * FROM user WHERE email=#{email}")
    UserDto findOneByEmail(@Param("email") String email);

    @Update("UPDATE user SET loginFailCount=loginFailCount+1 WHERE email=#{email}")
    void updateLoginFailCountByEmail(@Param("email") String email);

    @Update("UPDATE user SET enabled=1 WHERE id=#{id}")
    void enableUserById(@Param("id") int id);

    @Update("UPDATE user SET enabled=0 WHERE id=#{id}")
    void disableUserById(@Param("id") int id);

    @Select("SELECT EXISTS (SELECT email FROM user WHERE email=#{email})")
    boolean existEmail(String email);

    @Update("UPDATE user SET password=#{password} WHERE email=#{email}")
    void updatePassByEmail(@Param("password") String password, @Param("email") String email);

    @Insert({
            "<script>",
            "INSERT INTO user_role VALUES ",
            "<foreach collection='roleIds' index='index' item='roleId' separator=','>(#{userId}, #{roleId})</foreach>",
            "</script>"
    })
    void grantRoles(@Param("userId") int userId, @Param("roleIds") List<Integer> roleIds);

    @Select("SELECT * FROM user")
    @Results({
            @Result(column = "first_name", property = "firstName"),
            @Result(column = "last_name", property = "lastName"),
            @Result(column = "create_time", property = "createTime"),
//          @Result(column = "get", property = "roles", javaType = List.class, many = @Many(select = "getRolesByUserId"))
    })
    List<UserDto> getUserList();

    @Select("SELECT r.get, r.name FROM role AS r INNER JOIN user_role AS ur ON r.get=ur.role_id WHERE ur.user_id=#{userId}")
    @Results({
            @Result(
                    column = "get",
                    property = "permissions",
                    javaType = List.class,
                    many = @Many(select = "com.j4dream.property.dao.RoleDao.getPermissionsByRoleId")
            )
    })
    List<RoleDto> getRolesByUserId(@Param("userId") String userId);

    @Delete("DELETE FROM user WHERE id=#{id}")
    void deleteUserById(@Param("id") int userId);

}
